package com.gy.education.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gy.education.R;
import com.kankan.wheel.widget.OnWheelChangedListener;
import com.kankan.wheel.widget.WheelView;

import org.xutils.common.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by 高岳 on 2016/7/6.
 * Describe:
 */
public class SelectTimeUtil {

    private Context context;

    private String[] years = new String[101];
    private String[] months = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月",
            "9月", "10月", "11月", "12月"};
    private int mIndexYear = 0;
    private static int mIndexMonth = 0;
    private int mIndexDay = 0;
    private int mIndexHour = 0;
    private int mIndexMinute = 0;
    private static int dayCount;
    private String[] days = null;
    private String[] hours = null;
    private String[] minutes = null;
    private Calendar c;

    public SelectTimeUtil(Context context) {
        this.context = context;

    }

    /**
     * 初始化时分秒数据
     */
    public void InitTime() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        for (int i = 0; i <= 100; i++) {
            years[i] = (year - i) + "年";
        }
        hours = new String[23];
        initHours();
        minutes = new String[59];
        initMinutes();
    }

    /**
     * 天数格式初始化
     */
    private void initDays() {
        for (int i = 0; i < days.length; i++) {
            if (i < 9) {
                days[i] = "0" + String.valueOf(i + 1) + "日";
            } else {
                days[i] = String.valueOf(i + 1) + "日";
            }
        }
    }

    /**
     * 小时格式初始化
     */
    private void initHours() {
        for (int i = 0; i < hours.length; i++) {
            if (i < 9) {
                hours[i] = "0" + String.valueOf(i + 1) + "时";
            } else {
                hours[i] = String.valueOf(i + 1) + "时";
            }
        }
    }

    /**
     * 分钟格式初始化
     */
    private void initMinutes() {
        for (int i = 0; i < minutes.length; i++) {
            if (i < 9) {
                minutes[i] = "0" + String.valueOf(i + 1) + "分";
            } else {
                minutes[i] = String.valueOf(i + 1) + "分";
            }
        }
    }

    /**
     * 显示时间对话框 年月日时分秒
     *
     * @param Year   年
     * @param Month  月
     * @param Day    日
     * @param Hour   时
     * @param Minute 分
     * @param tvTime textview，用于显示
     */
    @SuppressLint("NewApi")
    public void dateWheelView(View parent, final int Year, final int Month,
                              int Day, int Hour, int Minute, final TextView tvTime) {
        mIndexYear = Year;
        mIndexMonth = Month;
        mIndexDay = Day;
        mIndexHour = Hour;
        mIndexMinute = Minute;
        dayCount = StringUtil.month(Integer.valueOf(mIndexYear),
                Integer.valueOf(mIndexMonth));
        InitTime();
        days = new String[dayCount];
        initDays();
        View ageView = LayoutInflater.from(context).inflate(
                R.layout.wb_dialog_wheelview, null);
        final PopupWindow popupWindow = new PopupWindow(context);
        popupWindow.setContentView(ageView);
        popupWindow.setWidth(LinearLayout.LayoutParams.FILL_PARENT);
        popupWindow.setHeight(LinearLayout.LayoutParams.FILL_PARENT);
        popupWindow.setFocusable(true);
        /** 年 */
        SelectYearWheelAdapter adapter = new SelectYearWheelAdapter(context,
                years);
        /** 月 */
        SelectYearWheelAdapter adapter1 = new SelectYearWheelAdapter(context,
                months);
        /** 日 */
        SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(context,
                days);
        /** 时 */
        SelectYearWheelAdapter adapter3 = new SelectYearWheelAdapter(context,
                hours);
        /** 分 */
        SelectYearWheelAdapter adapter4 = new SelectYearWheelAdapter(context,
                minutes);
        final WheelView wv_age = (WheelView) ageView
                .findViewById(R.id.wheelview);
        final WheelView wv_age1 = (WheelView) ageView
                .findViewById(R.id.wheelview1);
        final WheelView wv_age2 = (WheelView) ageView
                .findViewById(R.id.wheelview2);
        final WheelView wv_age3 = (WheelView) ageView
                .findViewById(R.id.wheelview3);
        final WheelView wv_age4 = (WheelView) ageView
                .findViewById(R.id.wheelview4);
        setBackground(wv_age);
        setBackground(wv_age1);
        setBackground(wv_age2);
        setBackground(wv_age3);
        setBackground(wv_age4);
        wv_age3.setVisibility(View.VISIBLE);
        wv_age4.setVisibility(View.VISIBLE);
        LinearLayout llMain = (LinearLayout) ageView
                .findViewById(R.id.wv_ll_main);
        Button bt_back = (Button) ageView.findViewById(R.id.wv_back);
        bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popupWindow.dismiss();
            }
        });
        Button bt_sure = (Button) ageView.findViewById(R.id.wv_sure);
        bt_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int year = wv_age.getCurrentItem();
                int month = wv_age1.getCurrentItem();
                int day = wv_age2.getCurrentItem();
                int hour = wv_age3.getCurrentItem();
                int minute = wv_age4.getCurrentItem();
                String changeString = (year + 2000) + "-" + (month + 1) + "-"
                        + (day + 1) + " " + (hour + 1) + ":" + (minute + 1);
                // TODO判断hour的值，然后对测量时段进行正确设置
                // setTvType(hour);
                Log.d("MainActivity", changeString);
                SimpleDateFormat format = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm");
                try {
                    if (format.parse(changeString).getTime() > System
                            .currentTimeMillis()) {
                        LogUtil.e( "您选择的日期大于当前日期，请正确选择！");
                    } else {
                        tvTime.setText(changeString);
                        popupWindow.dismiss();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        wv_age.setViewAdapter(adapter);
        wv_age1.setViewAdapter(adapter1);
        wv_age2.setViewAdapter(adapter2);
        wv_age3.setViewAdapter(adapter3);
        wv_age4.setViewAdapter(adapter4);
        wv_age.setCyclic(true);
        wv_age1.setCyclic(true);
        wv_age2.setCyclic(true);
        wv_age3.setCyclic(false);
        wv_age4.setCyclic(false);
        wv_age.setVisibleItems(5);
        wv_age1.setVisibleItems(5);
        wv_age2.setVisibleItems(5);
        wv_age3.setVisibleItems(5);
        wv_age4.setVisibleItems(5);
        wv_age.setCurrentItem(Year - 2000);
        wv_age1.setCurrentItem(Month - 1);
        wv_age2.setCurrentItem(Day - 1);
        wv_age3.setCurrentItem(Hour - 1);
        wv_age4.setCurrentItem(Minute - 1);
        wv_age.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub

                dayCount = StringUtil.month(Integer.valueOf(newValue + 2000),
                        Integer.valueOf(mIndexMonth));
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                int data_old_item = wv_age2.getCurrentItem();
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wv_age2.setViewAdapter(adapter2);
                wv_age2.setCyclic(true);
                if (data_old_item > (dayCount - 1)) {
                    wv_age2.setCurrentItem(dayCount - 1);
                } else {
                    wv_age2.setCurrentItem(data_old_item);
                }
                wv_age2.postInvalidate();
                wv_age2.refreshDrawableState();
            }
        });
        wv_age1.addChangingListener(new OnWheelChangedListener() {// 月份改变，每月天数跟着改变

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                mIndexMonth = newValue + 1;
                dayCount = StringUtil.month(Integer.valueOf(mIndexYear),
                        Integer.valueOf(newValue + 1));
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                int data_old_item = wv_age2.getCurrentItem();
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wv_age2.setViewAdapter(adapter2);
                wv_age2.setCyclic(true);
                if (data_old_item > (dayCount - 1)) {
                    wv_age2.setCurrentItem(dayCount - 1);
                } else {
                    wv_age2.setCurrentItem(data_old_item);
                }
                wv_age2.postInvalidate();
                wv_age2.refreshDrawableState();
            }
        });
        wv_age2.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                Log.e("", dayCount + "");
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wheel.setViewAdapter(adapter2);
                wheel.setCyclic(true);
                // wv_age2.postInvalidate();
            }
        });

        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x90000000);
        popupWindow.setBackgroundDrawable(dw);
        TranslateAnimation anim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f);
        anim.setDuration(500);
        llMain.setAnimation(anim);
        // popupWindow.setAnimationStyle(R.style.popupAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    private void setBackground(WheelView wv_age) {
        wv_age.setWheelBackground(R.color.white);
        wv_age.setWheelForeground(R.mipmap.ic_add_eat_wheel_foreground);
    }

    /**
     * 显示时间对话框 年月日
     *
     * @param parent   父类控件
     * @param Year     年
     * @param Month    月
     * @param Day      日
     * @param listener 监听用于传参
     */
    public void selectYearMonthDay(View parent, final int Year,
                                   final int Month, int Day, final SelectTtimeListener listener) {
        mIndexYear = Year;
        mIndexMonth = Month;
        mIndexDay = Day;
        dayCount = StringUtil.month(Integer.valueOf(mIndexYear),
                Integer.valueOf(mIndexMonth));
        InitTime();
        days = new String[dayCount];
        initDays();
        View view = LayoutInflater.from(context).inflate(
                R.layout.pop_select_year_month_day, null);
        final PopupWindow popupWindow = new PopupWindow(context);
        popupWindow.setContentView(view);
        popupWindow.setWidth(LinearLayout.LayoutParams.FILL_PARENT);
        popupWindow.setHeight(LinearLayout.LayoutParams.FILL_PARENT);
        popupWindow.setFocusable(true);

        final WheelView wv_age = (WheelView) view
                .findViewById(R.id.pop_select_ymd_wv_year);
        final WheelView wv_age1 = (WheelView) view
                .findViewById(R.id.pop_select_ymd_wv_month);
        final WheelView wv_age2 = (WheelView) view
                .findViewById(R.id.pop_select_ymd_wv_day);
        setYMD(view, Year, Month, Day, wv_age, wv_age1, wv_age2);
        LinearLayout llMain = (LinearLayout) view
                .findViewById(R.id.pop_select_ymd_ll_main);
        TextView btnCancel = (TextView) view
                .findViewById(R.id.pop_select_ymd_btn_back);
        TextView btnOK = (TextView) view
                .findViewById(R.id.pop_select_ymd_btn_sure);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popupWindow.dismiss();
            }
        });
        btnOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int year = wv_age.getCurrentItem();
                int month = wv_age1.getCurrentItem();
                int day = wv_age2.getCurrentItem();
                String changeString = (2016 - year) + "-" + (month + 1) + "-"
                        + (day + 1);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if (format.parse(changeString).getTime() > System
                            .currentTimeMillis()) {
                        LogUtil.e("您选择的日期大于当前日期，请正确选择！");
                    } else {
                        popupWindow.dismiss();
                        listener.setTime(2016 - year, month + 1, day + 1, 0, 0);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x90000000);
        popupWindow.setBackgroundDrawable(dw);
        TranslateAnimation anim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f);
        anim.setDuration(500);
        llMain.setAnimation(anim);
        // popupWindow.setAnimationStyle(R.style.popupAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 选择年月日的设置adapter及view
     */
    public void setYMD(View view, final int Year, final int Month, int Day,
                       final WheelView wv_age, final WheelView wv_age1,
                       final WheelView wv_age2) {
        /** 年 */
        SelectYearWheelAdapter adapter = new SelectYearWheelAdapter(context,
                years);
        /** 月 */
        SelectYearWheelAdapter adapter1 = new SelectYearWheelAdapter(context,
                months);
        /** 日 */
        SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(context,
                days);

        setBackground(wv_age);
        setBackground(wv_age1);
        setBackground(wv_age2);
        wv_age.setViewAdapter(adapter);
        wv_age1.setViewAdapter(adapter1);
        wv_age2.setViewAdapter(adapter2);
        wv_age.setCyclic(true);
        wv_age1.setCyclic(true);
        wv_age2.setCyclic(true);
        wv_age.setVisibleItems(5);
        wv_age1.setVisibleItems(5);
        wv_age2.setVisibleItems(5);
        wv_age.setCurrentItem(Year - 2000);
        wv_age1.setCurrentItem(Month - 1);
        wv_age2.setCurrentItem(Day - 1);
        wv_age.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                mIndexYear = newValue + 1;
                dayCount = StringUtil.month(Integer.valueOf(newValue + 2000),
                        Integer.valueOf(mIndexMonth));
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                int data_old_item = wv_age2.getCurrentItem();
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wv_age2.setViewAdapter(adapter2);
                wv_age2.setCyclic(true);
                if (data_old_item > (dayCount - 1)) {
                    wv_age2.setCurrentItem(dayCount - 1);
                } else {
                    wv_age2.setCurrentItem(data_old_item);
                }
                wv_age2.postInvalidate();
                wv_age2.refreshDrawableState();
            }
        });
        wv_age1.addChangingListener(new OnWheelChangedListener() {// 月份改变，每月天数跟着改变

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                mIndexMonth = newValue + 1;
                dayCount = StringUtil.month(Integer.valueOf(mIndexYear),
                        Integer.valueOf(newValue + 1));
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                int data_old_item = wv_age2.getCurrentItem();
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wv_age2.setViewAdapter(adapter2);
                wv_age2.setCyclic(true);
                if (data_old_item > (dayCount - 1)) {
                    wv_age2.setCurrentItem(dayCount - 1);
                } else {
                    wv_age2.setCurrentItem(data_old_item);
                }
                wv_age2.postInvalidate();
                wv_age2.refreshDrawableState();
            }
        });
        wv_age2.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                // dayCount = StringUtil.month(Integer.valueOf(mIndexYear),
                // Integer.valueOf(newValue + 1));
                days = new String[dayCount];
                initDays();
                for (int i = 0; i < dayCount; i++) {
                    days[i] = i + 1 + "日";
                }
                SelectYearWheelAdapter adapter2 = new SelectYearWheelAdapter(
                        context, days);
                wheel.setViewAdapter(adapter2);
                wheel.setCyclic(true);
            }
        });

    }

}
